<template>
	<wsPage :title="$t('Permission.customerServiceSettings')">
		<wsPanel>
			<template slot="panel_head_title">{{$t('Permission.customerServiceSettings')}}</template>
			<div slot="panel_body" class="profile-div">
				<div class="profile-form">
					<Alert type="error" v-if="!configLoad">客服配置错误无法初始化</Alert>
					<Form :label-width="100" ref="form1" :model="form1.model" :rules="form1.rules" v-if="configLoad">
						<FormItem :label="$t('Permission.customerServiceNickname')" prop="nickName">
							{{form1.model.nickName}}
						</FormItem>
						<FormItem :label="$t('Permission.customerServiceLogo')" required>
							<ws-upload-cos
						        ref="upload"
						        catelog="im"
						        :cfile-key="form1.upload.fileKey"
						        :show-upload-list="false"
						        :format="['jpg','jpeg','png']"
						        :max-size="2048"
						        :on-success="logoUploadSuccess"
						        type="drag"
						        style="display: inline-block;width:60px;">
						        <div style="width: 58px;height:58px;line-height: 58px;">
									<img :src="form1.model.logo" width="58px" height="58px" v-if="form1.model.logo"/>
									<Icon type="camera" size="20" v-else></Icon>
								</div>
						    </ws-upload-cos>
						</FormItem>
						<FormItem :label="$t('Permission.memberList')" required>
							<wsSmPanel>
								<div slot="list_operate">
									<Button @click="showAddModal">{{$t('Permission.addMember')}}</Button>
								</div>
								<div slot="list_data">
									<ws-table :data="table.datas" style="width: 100%">
										<ws-table-column align="center" prop="nickName" :label="$t('Permission.chatMember')"></ws-table-column>
										<ws-table-column align="center" prop="loginName" :label="$t('Permission.memberAccount')"></ws-table-column>
										<ws-table-column align="center" prop="userName" :label="$t('Permission.memberName')"></ws-table-column>
										<ws-table-column align="center" :label="$t('Permission.customerServiceLanguage')">
											<template slot-scope="scope">
												<span>{{scope.row.motherTongue}}/{{scope.row.english}}</span>
											</template>
										</ws-table-column>
										<ws-table-column align="center" prop="createDate" :label="$t('Permission.addTime')"></ws-table-column>
										<ws-table-column align="center" width="120" :label="$t('Permission.operating')">
											<template slot-scope="scope">
												<Button @click="delConfirm(scope.row)" type="text" size="small">{{$t('Permission.delete')}}</Button>
					      					</template>
										</ws-table-column>
									</ws-table>
								</div>
							</wsSmPanel>
						</FormItem>
					</Form>
				</div>
			</div>
		</wsPanel>
		<!--新增弹框-->
		<wsModal v-model="modal1.show" :ok-text="$t('Permission.save')" :cancelText="$t('Permission.cancel')" :title="$t('Permission.addCustomerMembers')" @on-ok="saveModal1" @on-cancel="cancelModal1">
		    <Form ref="modal1" :model="modal1.model" :rules="modal1.rules" :label-width="100">
		        <FormItem :label="$t('Permission.nickname')" prop="nickName">
		        	<Input v-model="modal1.model.nickName"></Input>
		        </FormItem>	
		        <FormItem :label="$t('Permission.memberAccount')" required>
		            <Col :span="12">
		            	<FormItem prop="roleId">
				            <Select v-model="modal1.model.roleId" :placeholder="$t('Permission.pleaseChoose')" @on-change="changeRole">
				            	<Option :value="-1">{{$t('Permission.SystemRole')}}</Option>
				                <Option :value="role.id" v-for="role in fields.roles">{{role.name}}</Option>
				            </Select>
				        </FormItem>
		            </Col>
		            <Col :span="12">
		            	<FormItem prop="userId">
				            <Select v-model="modal1.model.userId" :placeholder="$t('Permission.pleaseChoose')">
				                <Option :value="user.id" v-for="user in fields.users">
				                	<span>{{user.userName}}</span>
				                	<span style="float:right;color:#ccc">{{user.loginName}}</span>
				                </Option>
				            </Select>
				        </FormItem>
		            </Col>
		        </FormItem>	
				<FormItem :label="$t('Permission.defaultServiceLanguage')" prop="langaugeCode">
		            <Select v-model="modal1.model.langaugeCode" :placeholder="$t('Permission.pleaseChoose')">
		                <Option v-for="item in fields.languages" :value="item.code" :key="item.code">{{ item.motherTongue }}({{item.english}})</Option>
		            </Select>
		        </FormItem>
		    </Form>			
		</wsModal>				
	</wsPage>
</template>

<script>
	import Util from '../../../../common/util.js';
	export default {
		data() {
			return {
				//资源是否加载成功
				configLoad: false,
				form1: {
					model: {
						id: '',
						nickName: '',
						logo: ''
					},
					rules: {
						nickName: [
							{ required: true, message: '请输入昵称',trigger:'blur'}
						]
					},
					upload: {
						fileKey: ''	
					}
				},
				table: {
					datas: []
				},
				modal1: {
					show: false,
					model: {
						userId: null,
						roleId: null,
						kefuId: null,
						nickName: null,
						langaugeCode: null
					},
					rules: {
						userId: [
							{ required: true, message: '请选择'}
						],
						roleId: [
							{ required: true, message: '请选择'}
						],
						nickName: [
							{ required: true, message: '请输入昵称',trigger:'blur'}
						],
						langaugeCode: [
							{ required: true, message: '请输入默认服务语言'}
						]
					}
				},
				fields: {
					roles: [],
					users: [],
					languages: []
				}
			}
		},
		computed: {
			
		},
		mounted() {
			this.loadLanguage();
			this.init();
			// 当前选择的语言版本
			let getCurrentLanguage=localStorage.getItem('currentLanguage');
			this.$i18n.locale=getCurrentLanguage;
			if(getCurrentLanguage=='en'){
				this.modal1.rules={
					nickName: [
							{ required: true, message: 'Please enter a nickname',trigger:'blur'}
						],
				}
			}

		},
		methods: {
			/**
			 * 加载商品语言
			 */
			loadLanguage() {
				const _this = this;
				this.axios.get('/ws/ops/v2/languages').then(response => {
					let res = response.data;
					if(0 === res.meta.code) {
						if(res.data.length > 0) {
							_this.fields.languages = res.data;
						}
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('加载语言失败:' + message_);
					}
				});
			},
			/**
			 * 初始化
			 */
			init() {
				const _this = this;
				this.axios.get('/ws/sys/kefu/single').then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.buildData(res.data);
						_this.configLoad = true;
					} else {
						_this.configLoad = false;
					}
				});				
			},
			/**
			 * 构建数据
			 */
			buildData(data_) {
				let kefu = data_.kefu;
				this.form1.model = {
					id: kefu.id,
					nickName: kefu.nickName,
					logo: kefu.logo
				};
				this.table.datas = data_.kefuUsers;
			},
			showAddModal() {
				if(Util.vad.isBlank(this.form1.model.logo)) {
					this.$Message.info('请先设置客服的LGOO~');
					return;
				}
				this.modal1.show = true;
				this.initAdd();
				this.initRoles();
			},
			initAdd() {
				this.modal1.model = {
					userId: null,
					roleId: null,
					kefuId: null
				};
			},
			/**
			 * 提交模态框
			 */
			submitModal1() {
				console.log(this.modal1.model);
				this.modal1.model.kefuId = this.form1.model.id;
				const _this = this;
				let postData_ = this.modal1.model;
				this.axios.post('/ws/sys/kefu/single', postData_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.$Message.success('添加客服成员成功');
						_this.cancelModal1();
						_this.init();
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('添加客服成员失败:' + message_);
					}
				});				
			},
			/**
			 * 保存模态框
			 */
			saveModal1() {
				this.$refs['modal1'].validate((valid) => {
                    if (valid) {
                        this.submitModal1();
                    } 
                });
			},
			/**
			 * 取消选人
			 */
			cancelModal1() {
				this.$refs['modal1'].resetFields();
				this.modal1.show = false;
			},
						/**
			 * 初始化角色
			 */
			initRoles() {
				const _this = this;
				this.axios.get('/ws/sys/roles').then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if (0 == resMeta.code) {
						_this.buildFiledRoles(res.data);
					} else {
						_this.$Message.warning(resMeta.message);
					}
				});				
			},
			/**
			 * 构建角色列表
			 */
			buildFiledRoles(data_) {
				this.fields.roles = data_;
			},
			/**
			 * 切换角色
			 */
			changeRole(value_) {
				const _this = this;
				if(null == value_) {
					return;
				}
				this.modal1.model.userId = null;
				this.axios.get('/ws/sys/new/role/users/' + value_).then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if (0 == resMeta.code) {
						_this.buildFiledUsers(res.data);
					} else {
						_this.$Message.warning(resMeta.message);
					}
				});		
			},
			buildFiledUsers(data_) {
				this.fields.users = data_;
			},
			/**
			 * 删除提示
			 */
			delConfirm(row_) {
				const _this = this;
				if(_this.$i18n.locale=='en'){
					this.$confirm({
						title: 'Alert',
						width: 300,
						content: 'Delete your bank records?',
						onOk: function() {
							_this.delTableRow(row_);
						}
					});	
				}else{
					this.$confirm({
						title: '操作提示',
						width: 300,
						content: '你确认删除本行记录吗?',
						onOk: function() {
							_this.delTableRow(row_);
						}
					});	
				}
							
			},
			/**
			 * 删除数据字典项目
			 */
		    delTableRow(rowItem_) { //删除行
		      let kefuId = this.form1.model.id;
		      let userId = rowItem_.userId;
		      const _this = this;
		      this.axios.delete('/ws/sys/kefu/single/user/' + kefuId + '/' + userId).then(function(response) {
		      		let res = response.data;
					if(0 === res.meta.code) {
						_this.$Message.success('删除记录成功');
						_this.init();
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('删除客服成员失败:' + message_);
					}
		      });
		    },
		    /**
		     * 上传LOGO成功
		     */
		    handleLogoUploadSuccess (res, file) {
		    	if(res.meta.code == 0) {
		    		let fileList = res.data.fileList;
		    		if(fileList && fileList.length > 0) {
		    			let uploadFile = fileList[0];
		    			this.updateLogo(uploadFile);
		    		}
		    	}
		    },
			/**
			 * LOGO上传成功
			 */
			logoUploadSuccess(response, file, fileList) {
				if(0 == response.meta.code) {
					this.form1.model.logo = response.data.pubFileUrl;
					this.form1.upload.fileKey = response.data.fileId;
					this.updateLogo(response.data);
				}
			},		    
		    /**
		     * 更新LOGO
		     */
		   	updateLogo(uploadFile) {
		   		const _this = this;
		   		let postData_ = {
		   			id: this.form1.model.id,
		   			logo: uploadFile.pubFileUrl
		   		};
				this.axios.put('/ws/sys/kefu/single/logo', postData_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('更新客服LOGO失败:' + message_);
					}
				});		   		
		   	}
		}
	}
</script>

<style scoped="scoped">
	.profile-div {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 45px 0px 45px 0;
	}
	.profile-form {
		width: 70%;
	}
</style>